<template>
	<view class="main">
		<view>
			<u-text text="登录" size="20"></u-text>
		</view>
		<view style="margin-top: 10px;">
			<u-form :model="loginForm">
				<u-form-item>
					<u--input placeholder="请输入用户名" v-model="loginForm.username"></u--input>
				</u-form-item>

				<u-form-item>
					<u--input placeholder="请输入密码" v-model="loginForm.password" type="password"></u--input>
				</u-form-item>

				<u-form-item>
					<u-row>
						<u-col span="7">
							<u--input placeholder="请输入验证码" v-model="loginForm.code"></u--input>
						</u-col>
						<u-col span="3" offset="1">
							<u-image :src="codeUrl" mode="heightFix" height="38px" @click="getCode()"></u-image>
						</u-col>
					</u-row>
				</u-form-item>

				<view style="margin-top: 10px;">
					<u-button type="primary" @click="handleLogin()">登录</u-button>
				</view>
				<view style="margin-top: 10px;">
					<u-button type="warning" @click="toRegister()">注册</u-button>
				</view>

			</u-form>
		</view>
	</view>
</template>

<script>
	import {
		getCodeImg,
		login
	} from '@/api/user/login.js'
	export default {
		data() {
			return {
				codeUrl: "",
				loginForm: {
					username: "zjw",
					password: "123456",
					code: "",
					uuid: ""
				},
			}
		},
		methods: {
			getCode() {
				getCodeImg().then(res => {
					this.codeUrl = "data:image/gif;base64," + res.img;
					this.loginForm.uuid = res.uuid;
				})
			},
			handleLogin() {
				login(this.loginForm).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						})
						uni.setStorageSync("token", res.data.access_token)
						setTimeout(
						function(){
							uni.switchTab({
								url: '/pages/main/index'
							})
						},2000)
					} else {
						this.getCode()
						uni.showModal({
							title: '提示',
							content: res.msg,
							showCancel: false
						})
					}
				})
			},
			toRegister() {
				uni.redirectTo({
					url: '/pages/register/index'
				})
			}
		},
		onLoad(options) {
			this.getCode();
		}
	}
</script>

<style>
	.main {
		margin: 10px 10px 10px 10px;
	}

	.login-code {
		width: 33%;
		height: 38px;
		float: left;
	}
</style>
